import { Button, Form, Input, Modal, Pagination, Table, message } from 'antd'
import React, { useEffect, useState } from 'react'
import { majorList, departmentsList } from '../../../api/common'
import * as student from '../../../api/base/student'
import useBseGeneraHook from '../../../components/BaseGeneraForm/hook';
import { BaseGeneraForm } from '../../../components';

const Student: React.FC = () => {
  const [formDataConfig, setFormDataConfig] = useState<any[]>([
    {
      type: 'Input',
      label: '学号',
      fieldName: 'studentNumber',
      placeholder: '请输入学号',
      rules: [{ required: true, message: '请输入学号' }]
    },
    {
      type: 'Input',
      label: '姓名',
      fieldName: 's_name',
      placeholder: '请输入姓名',
      rules: [{ required: true, message: '请输入姓名' }]
    },
    {
      type: 'Input',
      label: '地址',
      fieldName: 's_address',
      placeholder: '请输入地址',
      rules: [{ required: true, message: '请输入地址' }]
    },
    {
      type: 'Radio',
      label: '性别',
      fieldName: 'gender',
      placeholder: '性别',
      child: [
        {
          label: '男',
          value: 0
        },
        {
          label: '女',
          value: 1
        },
        {
          label: '保密',
          value: 2
        }
      ]
    },
    {
      type: 'Select',
      label: '学院',
      fieldName: 'department_id',
      placeholder: '请选择学院',
      rules: [{ required: true, message: '请选择学院' }],
      child: []
    },
    {
      type: 'Select',
      label: '专业',
      fieldName: 'major_id',
      placeholder: '请选择专业',
      rules: [{ required: true, message: '请选择专业' }],
      child: []
    },
  ])
  const { open, edit, rowId, openModal, closeModal, addModal, editModal, rowIdSelect, formRef } = useBseGeneraHook()
  const [formData, setFormData] = useState<any>()
  const [list, setList] = useState<any[]>([])
  const [total, setTotal] = useState<number>(0)
  const [search, setSearch] = useState({ limit: 10, page: 1 })


  const getList = async () => {
    const res = await student.list(search).catch(err => console.log(err))
    setList(res.data.content)
    setTotal(res.data.totalElements)
  }

  const selectData = async () => {
    const res = await majorList().catch(err => console.log(err)) as any
    const res1 = await departmentsList().catch(err => console.log(err)) as any
    formDataConfig.forEach(item => {
      if (item.fieldName === 'department_id') {
        item.child = res.data
      }
      if (item.fieldName === 'major_id') {
        item.child = res1.data
      }
    })
  }

  useEffect(() => {
    selectData()
  }, [])

  useEffect(() => {
    getList()
  }, [search])

  const onFinish = (value: any) => {
    setSearch(value)
  }
  const reset = () => {
    setSearch({ limit: 10, page: 1, blur: null })
    formRef.current?.resetFields();
  }

  const add = () => {
    openModal()
    addModal()
  }
  const rowEdit = (record: any) => {
    openModal()
    editModal()
    rowIdSelect(record.sid)
    record.department_id = record.department.id
    record.major_id = record.major.id
    setFormData(record)
  }
  const del = async (val: any) => {
    Modal.confirm({
      title: '确定删除',
      icon: null,
      okText: '是',
      cancelText: '否',
      onOk() {
        student.del(val.sid).then(res => {
          if (res.success) {
            getList()
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  const emitOnFinish = async (value: any, isAdd: boolean) => {
    let res: any = ''
    if (isAdd) {
      res = await student.created(value).catch(err => console.log(err))
    } else {
      res = await student.update(rowId, value).catch(err => console.log(err))
    }
    if (res.success) {
      isAdd ? message.success('添加成功') : message.success('更新成功')
      getList()
      closeModal()
    }
  }

  const onChange = (page: number, pageSize: number) => {
    setSearch({ ...search, page: page || 1, limit: pageSize })
  }
  return (
    <>
      <div>
        <Form layout='inline' onFinish={onFinish} ref={formRef}>
          <Form.Item label="综合搜索" name="blur">
            <Input placeholder="请输入搜索内容" allowClear />
          </Form.Item>
          <Form.Item >
            <Button type="primary" htmlType="submit">搜索</Button>
            &nbsp;&nbsp;&nbsp;
            <Button type="primary" onClick={add}>添加</Button>
            &nbsp;&nbsp;&nbsp;
            <Button type="dashed" onClick={reset}>重置</Button>
          </Form.Item>
        </Form>
      </div >

      <div>
        <Table dataSource={list} pagination={false} rowKey="sid"
          columns={[
            {
              title: '学号',
              dataIndex: 'studentNumber',
              key: 'studentNumber',
            },
            {
              title: '姓名',
              dataIndex: 's_name',
              key: 's_name',
            },
            {
              title: '地址',
              dataIndex: 's_address',
              key: 's_address',
            },
            {
              title: '姓名',
              dataIndex: 's_name',
              key: 's_name',
            },
            {
              title: '专业',
              key: 'option',
              render: (_: any, record: any) => (
                <>
                  <span>{record.major.name}</span>
                </>
              )
            },
            {
              title: '学院',
              key: 'option',
              render: (_: any, record: any) => (
                <>
                  <span>{record.department.name}</span>
                </>
              )
            },
            // {
            //   title: '班级',
            //   key: 'option',
            //   render: (_: any, record: any) => (
            //     <>
            //       <span>{record?.classInfo.name}</span>
            //     </>
            //   )
            // },
            {
              title: '操作',
              key: 'option',
              render: (_: any, record: any) => (
                <>
                  <Button type="primary" onClick={() => rowEdit(record)}>编辑</Button>
                  <>&nbsp;</>
                  <Button type="primary" onClick={() => del(record)}>删除</Button>
                </>
              ),
            },
          ]}
        />
      </div>

      <div><Pagination showSizeChanger={true} total={total} onChange={onChange} /></div>

      <BaseGeneraForm
        title={edit ? '创建班级' : '查看班级'}
        open={open}
        isAdd={edit}
        footer={null}
        formData={formData}
        formDataConfig={formDataConfig}
        emitOnFinish={emitOnFinish}
        onCancel={closeModal} />
    </>
  )
}

export default Student
